package net.sf.rose.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import net.sf.rose.jdbc.UserBean;

import org.apache.log4j.Logger;

/**
 * @author fengjian
 * @since 2013-4-8
 */
public class OnlineUserListener implements HttpSessionListener {

	private static Logger logger = Logger.getLogger(OnlineUserListener.class);

	/** 静态变量存储所有在线用户信息 */
	private static Map<String, UserBean> onlineUsers = null;

	static {
		onlineUsers = new HashMap<String, UserBean>();
	}

	/**
	 * 取得所有在线用户信息
	 */
	public static Map<String, UserBean> getOnlineUsers() {
		return onlineUsers;
	}

	/**
	 * 取得在线用户信息
	 */
	public static UserBean getOnlineUser(HttpServletRequest request) {
		return onlineUsers.get(request.getSession().getId());
	}

	/**
	 * 
	 */
	public void sessionCreated(HttpSessionEvent event) {
		UserBean user = new UserBean();
		user.setUserName("访客");
		user.setLastLoginTime(new java.sql.Timestamp((new Date()).getTime()));
		onlineUsers.put(event.getSession().getId(), user);
		event.getSession().setAttribute(WebUtils.SYSTEM_USER, user);
		event.getSession().setMaxInactiveInterval(200);
		logger.info("新建session:" + user.getUserName());
	}

	/**
	 * 
	 */
	public void sessionDestroyed(HttpSessionEvent event) {
		UserBean user = onlineUsers.remove(event.getSession().getId());
		if (user != null) {
			logger.info(user.getUserName() + "已经退出！");
		}
	}

}
